package com.csxy.news.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WebUtil {

	public static final String INCLUDE_REQUEST = "includeRequest";
	public static final String FORWORD_REQUEST = "forwardRequest";
	
	public static final String USER = "user";
	public static final String USER_LIST = "userList";
	public static final String PAGE_SIZE = "pageSize";
	public static final String PAGE_INDEX = "pageIndex";
	public static final String PAGER = "pager";
	public static final String QUERY_FIELD = "queryField";
	public static final String QUERY_PARAM = "queryParam";
	public static final String OP = "op";
	public static final String OP_LIST = "list";
	public static final String OP_QUERY = "query";
	public static final String OP_ADD = "add";
	public static final String OP_DEL = "del";
	public static final String OP_UPDATE = "update";
	public static final String OP_FAIL = "fail";
	public static final String OP_OK = "ok";
	public static final String FRAGMENT = "fragment";
	public static final String OP_SHOW = "show";
	public static final String USERNAME = "username";
	public static final String PASSWORD = "password";
	public static final String CHARACTER_ENCODING = "encoding";
	public static final String WIDTH = "width";
	public static final String HEIGHT = "height";
	public static final String VERIFY_CODE = "verifyCode";
	public static final String BASE_PATH = "basePath";

	public static void saveLoginUser(HttpServletRequest request, Object u) {
		request.getSession().setAttribute(USER, u);
	}

	// 判断用户是否已经登录
	public static boolean checkLoginUser(HttpServletRequest req) {
		Object o = req.getSession().getAttribute(USER);
		return null != o;
	}

	// 获取登录对象
	@SuppressWarnings("unchecked")
	public static <T> T getLoginUser(HttpServletRequest req) {
		Object o = req.getSession().getAttribute(USER);
		return (T) o;
	}

	public static boolean isAjaxRequest(HttpServletRequest request){  
	    String header = request.getHeader("X-Requested-With");  
	    boolean isAjax = "XMLHttpRequest".equals(header) ? true:false;  
	    return isAjax;  
	}  
	
	public static boolean isIncludeRequest(HttpServletRequest request){
		Object o=request.getAttribute(WebUtil.INCLUDE_REQUEST);
		return null!=o;
	}
	
	public static boolean isForwardRequest(HttpServletRequest request){
		Object o=request.getAttribute(WebUtil.FORWORD_REQUEST);
		return null!=o;
	}
	
	// 将*.jsp请求转发给对应的*.sevlet处理
	public static void includeServlet(ServletRequest request, ServletResponse response, String urlPattern) {
		HttpServletRequest req = (HttpServletRequest) request;
		//对于所有的ajax请求都不要进行拦截
		if(!isAjaxRequest(req)){

			String path = req.getServletPath();
	           
			String servletPath = path.replaceFirst("(\\.jsp)", urlPattern);

			try {
				RequestDispatcher requestDispatcher = req.getRequestDispatcher(servletPath);
				//判断是否有对应的servlet
				if (null!=requestDispatcher) {
                   					
					//设置一个标记：说明servlet请求是通过*.jsp拦截到达的
					request.setAttribute(INCLUDE_REQUEST, true);
					
					requestDispatcher.include(request, response);
					//清除该标记
					request.removeAttribute(INCLUDE_REQUEST);
					
				}
			} catch (Exception e) {
			}
	
		}
		
	}

	public static String strCookie(HttpServletRequest request, String key, String defaultValue) {

		Cookie[] cookies = request.getCookies();
		if (null == cookies) {
			return defaultValue;
		}
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(key)) {
				return cookie.getValue();
			}
		}

		return defaultValue;

	}

	public static Integer intCookie(HttpServletRequest request, String key, Integer defaultValue) {

		String value = strCookie(request, key, "");
		try {
			return Integer.parseInt(value);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			return defaultValue;
		}

	}
	public static Boolean booleanCookie(HttpServletRequest request, String key, Boolean defaultValue) {
		
		String value = strCookie(request, key, "");
		try {
			return Boolean.parseBoolean(value);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			return defaultValue;
		}
		
	}

	public static String strParam(HttpServletRequest request, String key, String defaultValue) {

		String value = request.getParameter(key);
		if (null == value) {
			value = defaultValue;
		}

		return value;

	}

	public static Integer intParam(HttpServletRequest request, String key, Integer defaultValue) {
		Integer value = defaultValue;

		String s = request.getParameter(key);
		if (null == s) {
			return defaultValue;
		}

		try {
			value = Integer.parseInt(s);
		} catch (NumberFormatException e) {
			value = defaultValue;
		}

		return value;

	}

	public static Boolean boolParam(HttpServletRequest request, String key, Boolean defaultValue) {

		Boolean value = defaultValue;

		String s = request.getParameter(key);
		if (null == s) {
			return defaultValue;
		}

		try {
			value = Boolean.parseBoolean(s);
		} catch (NumberFormatException e) {
			value = defaultValue;
		}

		return value;

	}

	// 从request中获取指定类型的参数值
	@SuppressWarnings("unchecked")
	public static <T> T param(String key, Class<T> clazz, HttpServletRequest request) {
		T ret = null;
		String s = request.getParameter(key);

		if (null == s) {
			return null;
		}

		if (clazz == String.class) {
			ret = (T) s;
		} else if (clazz == Integer.class) {
			Integer i = Integer.parseInt(s);
			ret = (T) i;
		} else if (clazz == Boolean.class) {
			Boolean b = Boolean.parseBoolean(s);
			ret = (T) b;
		} else if (clazz == Float.class) {
			Float f = Float.parseFloat(s);
			ret = (T) f;
		} else if (clazz == Double.class) {
			Double d = Double.parseDouble(s);
			ret = (T) d;
		} else {
			throw new RuntimeException("无效参数值");
		}

		return ret;
	}

	/**
	 * 
	 * @param context
	 *            上下文本对象，它是可以在多个方法之间共享数据的全局对象
	 * @param filename
	 * @param tag
	 *            EL表达式中的变量名称 ${tag} 返回新的文件路径
	 */
	public static String replaceFile(ServletContext context, String filename, String tagName) {

		Object o = context.getAttribute(tagName);
		// 如果存在对应的值，就转成字符串，否则为空串
		String tagValue = null != o ? o.toString() : "";

		String path = context.getRealPath(filename);
		String newPath = context.getRealPath("x" + filename);

		try {
			// 读取文件的内容filename
			FileReader fr = new FileReader(path);
			BufferedReader br = new BufferedReader(fr);
			StringBuffer sb = new StringBuffer();
			String lines;
			while ((lines = br.readLine()) != null) {
				sb.append(lines);
			}
			br.close();
			// 将${tagName}用tagValue来替换
			String str = sb.toString().replaceAll("\\$\\{" + tagName + "\\}", tagValue);
			// 再将内容写回到文件filename
			FileWriter fw = new FileWriter(newPath);
			fw.write(str);
			fw.close();
			Thread.sleep(300);
		} catch (Exception e) {
			// TODO: handle exception
		}

		return "x" + filename;

	}

	//保存验证码
	public static void saveVerifyCode(HttpServletRequest request, String verifyCode) {
		
		request.getSession().setAttribute(VERIFY_CODE, verifyCode);
		
	}
    //检测验证码
	public static boolean checkVerifyCode(HttpServletRequest request, String verifyCode) {
		
		Object o=request.getSession().getAttribute(VERIFY_CODE);
		
		return null!=o && o.toString().equalsIgnoreCase(verifyCode);
	}

	public static void noCache(HttpServletResponse response) {
		
		response.setHeader("Pragma", "No-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);
  	
	}

	public static void useImageContentType(HttpServletResponse response) {
		response.setContentType("image/jpeg");
		// TODO Auto-generated method stub
		
	}

	public static void useJsonContentType(HttpServletResponse response) {
		response.setContentType("application/json");
		// TODO Auto-generated method stub
		
	}

	//设置jsp的基路径，用于设置jsp页的base标签
	public static void buildBasePath(HttpServletRequest request) {
		//构建请求的基路径
    	StringBuffer sb=new StringBuffer();
    	sb.append(request.getScheme())
    	  .append("://").append(request.getServerName())
    	  .append(":").append(request.getServerPort())
          .append(request.getContextPath()).append("/");
    	
    	//将基路径保存到请求上下文对象中，用于在jsp页中设置basepath
    	request.setAttribute(BASE_PATH, sb.toString());
    	
	}

	//判断请求的op参数的值中是否是指定的内容
	public static boolean isOP(String op, HttpServletRequest request) {
		
		String s=request.getParameter(OP);
		
		return null!=s && s.equals(op);
	}
	

}
